import { glob } from 'glob'
import config, { saveConfig } from '../config/index.js'
import dbWeb from '../lib/doubao/doubao-web.js'
import fsPromises from 'fs/promises'
import { extractPrompt, rubyExtractPrompt } from '../lib/llm/prompt.js'
import path from 'path'

import { sleep } from '../util.js'

class API {
  // 提取渗透攻击方法与缓解措施
  async extractDetectionAndMitigation(ctx) {
    ctx.body = 'success'

    setTimeout(async () => {
      const data = config.chat.ruby
      let files = await glob(data.src)

      console.log('files', files.length)

      for (let i = data.index; i < files.length; i++) {
        // 进度
        console.log(`${i}/${files.length}`, ((i / files.length) * 100).toFixed(2))

        data.index = i
        saveConfig()

        const text = await fsPromises.readFile(files[i], 'utf-8')
        const outputPath = path.join(data.dist, path.parse(files[i]).name + '-' + Date.now())

        let prompt = rubyExtractPrompt + text

        const dirs = files[i].split('\\')
        const modulesIndex = dirs.indexOf('modules')
        const moduleType = dirs[modulesIndex + 1]

        prompt = prompt
          .replaceAll('{moduleName}', path.parse(files[i]).name)
          .replaceAll('{moduleType}', moduleType)

        const result = await dbWeb.prompt(prompt)

        try {
          // 转义处理
          const fixedResult = result
            .replace(/\\([^"\\/bfnrtu])/g, '\\\\$1')
            // 零宽空格/不可见控制字符
            .replace(/[\u200B-\u200D\uFEFF]/g, '')

          console.log('fixedResult', fixedResult)

          const json = JSON.parse(fixedResult)

          await fsPromises.writeFile(outputPath + '.json', JSON.stringify(json.extract, null, 2))
        } catch (e) {
          console.error('json parse error，直接保存', e)
          fsPromises.writeFile(outputPath + '-error.json', result)
        }

        await sleep(45 * 1000)
      }
    }, 500)
  }
}

export default new API()
